package com.learn.concurrent.blockingqueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author wangxing
 * @version 2020/8/16 22:41 Administrator
 */

public class NumberProducer implements Runnable {
    Logger logger = LoggerFactory.getLogger(NumberProducer.class);
    private BlockingQueue<Integer> numbersQueue;
    private final Integer poisonPill;
    private final Integer poisonPillPerProducer;

    public NumberProducer(BlockingQueue<Integer> numbersQueue, Integer poisonPill, Integer poisonPillPerProducer) {
        this.numbersQueue = numbersQueue;
        this.poisonPill = poisonPill;
        this.poisonPillPerProducer = poisonPillPerProducer;
    }


    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        try {
            generateNumbers();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void generateNumbers() throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            int num = ThreadLocalRandom.current().nextInt(100);
            numbersQueue.put(num);
            logger.info("生产者:{},将数{}放入到阻塞队列中",Thread.currentThread().getId(),num);
        }
        for (int i = 0; i < poisonPillPerProducer; i++) {
            numbersQueue.put(poisonPill);
            logger.info("线程{},向队列中插入第{}个毒药", Thread.currentThread().getId(),i+1);
        }
    }
}
